/**
 * 公共js部分
 * Created by wangzijie on 16/9/10.
 */
'use strict';

//字符串startsWith函数
/*if (typeof String.prototype.startsWith !== 'function') {
 String.prototype.startsWith = function (str) {
 return new RegExp("^" + str).test(this);
 };
 }*/

/**
 * APP版本
 */
var APP_CODE = 1;

/**
 * API失败
 */
var API_ERROR = "9999";

/**
 * API登录授权失效或是未登录
 */
var API_NO_LOGIN = "9998";

/**
 * API请求次数太多，限制请求
 */
var API_FORBIDDEN = "9997";

/**
 * API成功
 */
var API_SUCCESS = "0000";

/**
 * 公共API地址
 * @type {string}
 */
//var API_PATH = 'http://192.168.1.105:8080';
var API_PATH = 'http://doumi.gaozhikeji.com/partner-api';

/**
 * 汇付请求地址
 * @type {string}
 */
var API_PNR_DISPATCHER = API_PATH + '/pnr/dispatcher';

/**
 * 公共静态资源地址
 * @type {string}
 */
var WEB_ROOT = location.href.split('/www/')[0] + '/www';

/*if (!location.href.startsWith('http')) {
 API_PATH = 'http:' + API_PATH;
 WEB_ROOT = 'http:' + WEB_ROOT;
 }*/

//测试环境打标志
var _temp_debug_flag = getQueryString('debug');
if (_temp_debug_flag) {
    setStorage('debug', _temp_debug_flag);
}
_temp_debug_flag = getStorage('debug');
if (_temp_debug_flag == 1 || _temp_debug_flag == 'true' || (typeof _temp_debug_flag === 'boolean' && _temp_debug_flag)) {
    debugConsole();
}

// .container 设置了 overflow 属性, 导致 Android 手机下输入框获取焦点时, 输入法挡住输入框的 bug
// 相关 issue: https://github.com/weui/weui/issues/15
// 解决方法:
// 0. .container 去掉 overflow 属性, 但此 demo 下会引发别的问题
// 1. 参考 http://stackoverflow.com/questions/23757345/android-does-not-correctly-scroll-on-input-focus-if-not-body-element
//    Android 手机下, input 或 textarea 元素聚焦时, 主动滚一把
if (/Android/gi.test(navigator.userAgent)) {
    window.addEventListener('resize', function () {
        if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
            window.setTimeout(function () {
                document.activeElement.scrollIntoViewIfNeeded();
            }, 0);
        }
    });
}

/**
 * 获取请求拼接参数
 * @param bizType
 * @param jsonData
 * @returns {*}
 */
function getRequestData(biz, jsonData) {
    jsonData = jsonData || {};
    var data = {
        version: "3.0", biz: biz, token: getLoginInfo('token') || '', platform: 2, data: jsonData
    };
    return JSON.stringify(data);
}

/**
 * ajax请求
 */
function ajaxRequest(ajaxParams, fnSuccess, fnError, noShowMessage, noShowLoading) {
    if (typeof ajaxParams === 'string') {
        ajaxParams = {
            data: ajaxParams
        };
    }

    var success = function (data) {
        layer.close(this.index);
        if (data.token && data.token != '') {
            setLoginInfo(data);
        }
        if (data.statusCode == API_SUCCESS) {
            fnSuccess && fnSuccess(data);
        } else if (data.statusCode == API_NO_LOGIN) {
            location.href = '#/login';
        } else {
            if (!noShowMessage) {
                mui.toast(data.message);
            }
            fnError && fnError(data);
        }

    };

    var error = function (xmlHttpRequest, textStatus, errorThrown) {
        console.log(arguments);
        layer.close(this.index);
        if (!noShowMessage) {
            mui.toast('网络异常，请检查网络');
        }
        fnError && fnError(xmlHttpRequest, textStatus, errorThrown);
    };

    var default_params = {
        dataType: 'json',
        cache: false,
        url: API_PATH + '/entrance',
        contentType: 'application/json',
        async: true,
        type: "POST", //crossDomain: true,
        success: success,
        error: error,
        beforeSend: function () {
            if (!noShowLoading) {
                this.layerIndex = layer.load(1);
            }
        },
        complete: function () {
            if (!noShowLoading) {
                layer.close(this.layerIndex);
            }
        }
    };

    ajaxParams = jQuery.extend(default_params, ajaxParams);
    return jQuery.ajax(ajaxParams);
}

/**
 * 设置登录信息
 * @param data
 */
function setLoginInfo(data) {
    if (isStorageSupported()) {
        if (data.token) {
            localStorage.setItem('token', data.token);
        }
    } else if (jQuery.cookie) {
        if (data.token) {
            jQuery.cookie('token', data.token);
        }
    }
}

/**
 * 获取登录信息
 * @param key
 * @returns {*}
 */
function getLoginInfo(key) {
    if (isStorageSupported()) {
        return localStorage.getItem(key);
    } else {
        return jQuery.cookie(key);
    }
}

/**
 * 获取登录客户
 */
function getLoginCustomer() {
    return JSON.parse(getStorage('customer') || '{}');
}

/**
 * 设置客户
 * @param customer
 */
function setLoginCustomer(customer) {
    setStorage('customer', JSON.stringify(customer));
}

/**
 * 退出登录
 */
function logout(action) {
    clearStorage('token');
    clearStorage('customer');
    var type = typeof action;
    if (type == 'string') {
        location.href = action;
    }
    if (type == 'function') {
        action();
    }
}

/**
 * 校验是否支持H5 storage IOS 的Safari 在无痕迹模式下是不支持的哦
 * @returns {boolean}
 */
function isStorageSupported() {
    var testKey = 'test', storage = window.sessionStorage;
    try {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return true;
    } catch (error) {
        return false;
    }
}

/**
 * 设置临时变量
 * @param key
 * @param value
 */
function setTempStorage(key, value) {
    if (isStorageSupported()) {
        sessionStorage.setItem(key, value);
    } else {
        jQuery.cookie(key, value);
    }
}

/**
 * 设置临时变量
 * @param key
 * @param value
 */
function setStorage(key, value) {
    if (isStorageSupported()) {
        localStorage.setItem(key, value);
    } else {
        jQuery.cookie(key, value);
    }
}

/**
 * 获取临时变量 同时决定是否清除
 * @param key
 * @param isClear
 * @returns {*}
 */
function getTempStorage(key, isClear) {
    var value = null;
    if (isStorageSupported()) {
        value = sessionStorage.getItem(key);
    } else {
        value = jQuery.cookie(key);
    }
    if (isClear) {
        clearTempStorage(key);
    }
    return value;
}

/**
 * 获取临时变量 同时决定是否清除
 * @param key
 * @param isClear
 * @returns {*}
 */
function getStorage(key, isClear) {
    var value = null;
    if (isStorageSupported()) {
        value = localStorage.getItem(key);
    } else {
        value = jQuery.cookie(key);
    }
    if (isClear) {
        clearStorage(key);
    }
    return value;
}

/**
 * 清楚临时变量
 * @param key
 */
function clearTempStorage(key) {
    if (isStorageSupported()) {
        if (key !== undefined) {
            sessionStorage.removeItem(key);
        } else {
            sessionStorage.clear();
        }
    } else {
        jQuery.cookie(key, '');
    }
}

/**
 * 清楚临时变量
 * @param key
 */
function clearStorage(key) {
    if (isStorageSupported()) {
        if (key !== undefined) {
            localStorage.removeItem(key);
        } else {
            localStorage.clear();
        }
    } else {
        jQuery.cookie(key, '');
    }
}

/**
 * 校验是否成功
 */
function checkLogin() {
    return !!getLoginInfo('token');
}

/**
 * 获取url查询参数
 * @param name
 * @returns {*}
 */
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var matchs = window.location.search.substr(1).match(reg);
    if (matchs != null) {
        return decodeURI(decodeURIComponent(matchs[2]));
    }
    return null;
}

/**
 * 是否是合法的手机号
 * @param mobile
 * @returns {boolean}
 */
function isMobile(mobile) {
    return /^1[3578]\d{9}$/.test(mobile);
}

/**
 * 创建debug
 */
function debugConsole() {
    var vConsoleScript = document.createElement('script');
    vConsoleScript.src = WEB_ROOT + '/js/vconsole.min.js';
    jQuery(document.scripts[0]).after(vConsoleScript);
}

/**
 * 初始化mui弹窗选择
 *
 * @param jqueryElement
 * @param data
 * @param options
 * @param fnSelected
 */
function initMuiPopPickerSelect(jqueryElement, data, options, fnSelected) {
    options = options || {};
    var picker;
    jqueryElement.on('tap', function () {
        var $this = jQuery(this);
        var picker = $this.data('picker');

        if (!picker) {
            picker = new mui.PopPicker(options);
            picker.setData(data);
            $this.data('picker', picker);
        }


        var selected = $this.data('selected') || [];

        function setDefaultValue(index) {
            if (index < selected.length) {
                picker.pickers[index].setSelectedValue(selected[index].value, 0, function () {
                    setDefaultValue(++index);
                });
            }
        }

        setDefaultValue(0);

        picker.show(function (items) {
            $this.data('selected', items);
            if (fnSelected && typeof fnSelected == 'function') {
                fnSelected.call($this, items);
            } else {
                var values = [];
                var texts = [];
                for (var i = 0; i < items.length; i++) {
                    values.push(items[i].value);
                    texts.push(items[i].text);
                }
                $this.val(texts.join(options.join || ''));

                $this.siblings(':hidden,*[data-child]').each(function (index) {
                    jQuery(this).val(values[index]);
                });
            }
            picker.dispose();
            $this.data('picker', null);
        });
    });
}

/**
 * 初始化mui弹窗选择
 *
 * @param jqueryElement
 * @param options
 * @param fnSelected
 */
function initMuiPopDatePickerSelect(jqueryElement, options, fnSelected) {
    jqueryElement.on('tap', function () {
        var $this = jQuery(this);
        var picker = $this.data('picker');
        if (!picker) {
            options = options || JSON.parse($this.data('options') || '{}');
            picker = new mui.DtPicker(options);
            $this.data('picker', picker);
        }
        picker.show(function (rs) {
            if (fnSelected && typeof fnSelected == 'function') {
                fnSelected(rs);
            } else {
                $this.data('select', rs);
                $this.val(rs.text);
            }

            picker.dispose();
            $this.data('picker', null);
        });
    });
}

/**
 * 自动生成表单并发送数据到指定地址
 *
 * @param url
 * @param data
 * @param method
 */
function sendPost(url, data, method) {
    mui.toast('第三方还未接通');
    return;
    method = method || 'POST';
    var html = '<form method="' + method + '" action="' + url + '">';
    jQuery.each(data, function (key, value) {
        html += '<input type="hidden" name="' + key + '" value="' + value + '" />';
    });
    html += '</form>';

    var form = jQuery(html);

    jQuery('body').append(form);
    form.trigger('submit');
    form.remove();
}

/**
 * 包装JSONobject发送请求
 * @param jsonObject 需要包装的jsonobject
 * @param needProperties 需要的属性数组
 */
function wrapPostData(jsonObject, needProperties) {
    var newJson = {};
    jQuery.each(needProperties || jsonObject, function (key, value) {
        var wrapKey = needProperties ? value : key;
        if (jsonObject[wrapKey]) {
            newJson[wrapKey] = jsonObject[wrapKey];
        }
    });
    return newJson;
}

/**
 * 搜索指定json数据中的某个指定key关键字对应的值
 *
 * @param json JSON数据
 * @param code 搜索的code值
 * @param codeKey code值对应的属性key
 * @param childKey 如果指定则搜索指定的子类集合
 * @returns {undefined}
 */
function searchJsonByCode(json, code, codeKey, childKey) {
    var data = undefined;
    codeKey = codeKey || 'value';
    jQuery.each(json, function (key, value) {
        if (value[codeKey] == code) {
            data = value;
            return false;
        }

        //寻找子类
        if (childKey && value[childKey]) {
            data = getPlaceData(value[childKey], code, codeKey, childKey);
            return !data;
        }
    });
    return data;
}

/**
 * 利用cordova上传文件
 * @param fileURL 本地文件地址
 * @param serverFold 上传到服务器的目录
 * @param fr 上传文件对象
 * @param fnSuccess 上传成功执行函数
 * @param fnError 上传失败执行函数
 * @param fileType 上传文件的mimetype
 * @param fileKey 上传到服务的资源文件可以，表单提交的参数名称
 */
function uploadByCordova(fileURL, serverFold, ft, fnSuccess, fnError, fileType, fileKey, serverUrl) {
    if (fileURL.lastIndexOf('?') >= 0) {
        fileURL = fileURL.substr(0, fileURL.length - fileURL.lastIndexOf('?') - 2);
    }
    fileURL = fileURL.replace('file://', '');
    var uri = encodeURI(serverUrl || (API_PATH + "/file/upload/" + serverFold));
    var options = new FileUploadOptions();
    options.fileKey = fileKey || "file";
    options.mimeType = fileType || "image/png";

    var ft = ft || new FileTransfer();
    options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);

    layer.load(1);
    ft.upload(fileURL, uri, function (data) {
        layer.closeAll();
        if (data.responseCode == 200) {
            fnSuccess && fnSuccess(JSON.parse(data.response));
        } else {
            mui.toast('上传文件失败');
            fnError && fnError(data);
        }
    }, function () {
        layer.closeAll();
        mui.toast('上传文件失败');
        fnError && fnError.apply(this, arguments);
    }, options);
    return ft;
}

/**
 * 相机工具类
 * @param options 参数
 * @param onSuccess 执行成功执行函数
 * @param onFail 执行失败执行函数
 */
function cameraUtils(options, onSuccess, onFail) {
    if (!onFail) {
        onFail = function () {
            mui.toast('打开相册/相机败');
        };
    }

    options = options || {};

    options = jQuery.extend({
        quality: 50,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
        encodingType: Camera.EncodingType.JPEG,
        mediaType: Camera.MediaType.PICTURE,
        allowEdit: false,
        correctOrientation: false
    }, options);

    navigator.camera.getPicture(function (file) {
        onSuccess(file);
    }, onFail, options);
}


/**
 * cordova视频工具
 *
 * @param options 参数
 * @param onSuccess 执行成功执行函数
 * @param onError 执行失败执行函数
 */
function videoUtil(options, onSuccess, onError) {
    if (!onError) {
        onError = function () {
            mui.toast('打开录像失败');
        };
    }

    options = options || {};
    options = jQuery.extend({
        limit: 1, duration: 30
    }, options);

    navigator.device.capture.captureVideo(function (mediaFiles) {
        var path = mediaFiles[0].fullPath;
        onSuccess(path, mediaFiles);
    }, onError, options);
}

//自适应
function setFontSize(maxWidth, minWidth, fontSize) {
    maxWidth = maxWidth || 640;
    minWidth = minWidth || 320;
    fontSize = fontSize || 40;
    var screenWidth = document.documentElement.clientWidth;
    if (screenWidth >= maxWidth) {
        screenWidth = maxWidth;
    } else if (screenWidth <= minWidth) {
        screenWidth = minWidth;
    }
    fontSize = screenWidth * fontSize / maxWidth;
    document.documentElement.style.fontSize = fontSize + 'px';
}

/**
 * 是否window访问
 * @returns {boolean}
 */
function is_window() {
    return navigator.userAgent.indexOf("Window") > 0;
}

/**
 * 判断是否是微信
 * @returns {boolean}
 */
function is_weixn() {
    var ua = navigator.userAgent.toLowerCase();
    var finds = ua.match(/MicroMessenger/i);
    return finds && finds[0] === "micromessenger";
}